package tice.convert;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class Setting extends PreferenceActivity {
	
	PreferenceScreen mPreferenceScreen;
	ProgressDialog mProgressdialog;
	boolean mCancel = false;
	
	final static int DIALOG_DOWNLOADING = 2;
	final static int DIALOG_DOWNLOADING_ERROR = 3;
	final static int DIALOG_DOWNLOADING_START = 4;
	final static int DOWNLOADING_FINISH = 1;
	final static int MAX_ERROR_TRY = Convert.Currency.length / 2;
	
	public static final String KEY_PREFERENCE_DOWNLOAD = "preference_download";
	
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.setting);
        
        mPreferenceScreen = (PreferenceScreen)getPreferenceScreen().findPreference(KEY_PREFERENCE_DOWNLOAD);
        
        LoadLastUpdateDate();
    }
    
    private void LoadLastUpdateDate(){
        SharedPreferences settings = getSharedPreferences(Convert.PREFS_NAME, 0);
        Date update = new Date(settings.getLong(Convert.PREFS_NAME_UPDATEDATE, 0));
        
        if(update.getTime() != 0){
        	mPreferenceScreen.setSummary(String.format("Last update: %s", update.toLocaleString()));
        }else {
        	mPreferenceScreen.setSummary(String.format("Never updated"));
        }
    }
    
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
	
        if (preference.getKey().equals(KEY_PREFERENCE_DOWNLOAD)) {
        	showDialog(DIALOG_DOWNLOADING_START);
        }
		
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	} 
	
    public void StartRefreshCurrency(){
    	Thread thr = new Thread(null, mTaskDownloading, "ConvertThread");
        thr.start();
    	showDialog(DIALOG_DOWNLOADING);
    }
    

    final Runnable mTaskDownloading = new Runnable() {
        public void run() { 
        	boolean ret = RefreshCurrency();
        	if(ret == true){
        		Message message = new Message();
	            message.what = DOWNLOADING_FINISH;
	            mHandler.sendMessage(message);
            }else {
        		Message message = new Message();
	            message.what = DIALOG_DOWNLOADING_ERROR;
	            mHandler.sendMessage(message);            	
            }
        }
    };
    
    private final Handler mHandler = new Handler() {
        @Override
         public void handleMessage(final Message msg) {
          if (msg.what == DOWNLOADING_FINISH){
        	  mProgressdialog.dismiss();
        	  LoadLastUpdateDate();
          }else if (msg.what == DIALOG_DOWNLOADING_ERROR){
        	  mProgressdialog.dismiss();
        	  showDialog(DIALOG_DOWNLOADING_ERROR);
          }
        }
    };    
    
 	private boolean RefreshCurrency(){

 		HttpGet request;  
 		HttpResponse response;  
 		HttpClient httpClient = new DefaultHttpClient();

 		float val = 0;
 		int status;
 		int errtime = 0;
 		int len = Convert.Currency.length - 2;
 		String url;
 		mCancel = false;

 		Date d = new Date();
        SharedPreferences settings = getSharedPreferences(Convert.PREFS_NAME, 0); 
        SharedPreferences.Editor editor = settings.edit(); 

 		for(int i= 2;i< len;i++){
 	 		try{
 	 			if (mCancel == true){
 	 				return true;
 	 			}
 	 			
 	 			url = String.format("http://www.google.com/ig/calculator?q=1USD%%3D%%3F%s", Convert.Currency[i]);
 	 			request = new HttpGet(url);
	 			response = httpClient.execute(request);
	 			
	 			status = response.getStatusLine().getStatusCode();  
	 			if (status != HttpStatus.SC_OK) {  
	 				val = 0;
	 			} else {  
	 				InputStream content = response.getEntity().getContent();  
	 				 val = getValuefromString(content);
	 			     if (val != 0){
	 			    	 editor.putFloat(Convert.Currency[i], val);
	 			    	 editor.commit();
	 			     }
	 			   content.close();
	 			}
	 			
	 			mProgressdialog.setProgress(i);
	 	 	} catch (IOException e){
	 	 		val = 0;
	 	 		errtime ++;
	 	 		
	 	 		if(errtime >= MAX_ERROR_TRY){
	 	 			return false;
	 	 		}
	 	 		
	 	 		continue;
	 	 	}
	 	}

 		if(val !=0 && errtime < MAX_ERROR_TRY){
	    	 editor.putLong(Convert.PREFS_NAME_UPDATEDATE, d.getTime());
	    	 editor.commit();
	    	 return true;
 		}
		
 		return false;
 	}

 	private float getValuefromString(InputStream is) throws IOException{
 		float value = 0;
 		String data,substr;
 		String result = inputStreamToString(is);
 		int firstindex = result.indexOf("rhs: \"");
 		int lastindex = result.lastIndexOf("\",error");
 		
 		if(firstindex + 6 == lastindex) return value;
 		
 		substr = result.substring(firstindex + 6, lastindex);
 		firstindex = substr.indexOf(" ");
 		data = substr.substring(0,firstindex);
 		data = data.replaceAll(String.valueOf((char)65533), "");
 		value = Float.valueOf(data);
 		
 		return value;
 	}

 	
 	private String inputStreamToString(InputStream is) throws IOException{
 		ByteArrayOutputStream  baos = new ByteArrayOutputStream();
 		int i=-1;
 		while((i=is.read())!=-1){
 			baos.write(i);
 		}
 		return baos.toString();
 	}
 	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
	        case DIALOG_DOWNLOADING: {
	        	mProgressdialog = new ProgressDialog(this);
	        	mProgressdialog.setMessage("Updating Currency Data");
	        	mProgressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
	        	mProgressdialog.setMax(Convert.Currency.length - 2);
	        	mProgressdialog.setCancelable(true);
	        	mProgressdialog.setOnCancelListener(new OnCancelListener(){
					@Override
					public void onCancel(DialogInterface dialog) {
						mCancel = true;
					}});
	        	return mProgressdialog;    
	        	}
	        case DIALOG_DOWNLOADING_ERROR: {
	            return new AlertDialog.Builder(this)
	            .setTitle("Update Error")
	            .setMessage("Couldn't update data")
	            .setPositiveButton("Retry", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                	StartRefreshCurrency();
	                }
	            })
	            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	            
	                }
	            })
	            .create();
	        }
	        case DIALOG_DOWNLOADING_START: {
	            return new AlertDialog.Builder(this)
	            .setTitle("Update Currency Data")
	            .setMessage("Would you like to update currency data?")
	            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                	StartRefreshCurrency();
	                }
	            })
	            .setNegativeButton("No", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	            
	                }
	            })
	            .create();
	        }
        }
        return null;
    }
}
